package com.lz.convertor;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lz.entity.OrderDetail;
import com.lz.entity.OrderMasterQuery;
import com.lz.enums.ResultEnum;
import com.lz.exception.SellException;
import com.lz.form.OrderForm;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单的表单对象转查询对象
 * Created by lz on 2018/8/22.
 */
@Slf4j
public class OrderForm2OrderMasterQueryConvertor {
    public static OrderMasterQuery convert(OrderForm orderForm){
        Gson gson = new Gson();

        OrderMasterQuery orderMasterQuery = new OrderMasterQuery();

        orderMasterQuery.setBuyerName(orderForm.getName());
        orderMasterQuery.setBuyerPhone(orderForm.getPhone());
        orderMasterQuery.setBuyerAddress(orderForm.getAddress());
        orderMasterQuery.setBuyerOpenid(orderForm.getOpenid());
        List<OrderDetail> orderDetails = new ArrayList<>();
        try{
            orderDetails = gson.fromJson(orderForm.getItems(),
                    new TypeToken<List<OrderDetail>>(){}.getType());
        } catch (Exception e){
            log.error("【对象转换】错误，string={}",orderForm.getItems());
            throw new SellException(ResultEnum.PARAM_ERROR);
        }
        orderMasterQuery.setOrderDetailList(orderDetails);
        return orderMasterQuery;
    }
}
